package dasregistry.ontology.browsing;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

/**
 * class to hold and change JSON data from ols ontology request and convert it
 * to jstree format
 * 
 * @author jw12
 * 
 */
public class JsonNode extends JSONObject {

	public static JsonNode createNew(JsonNode node) {
		JsonNode obj = new JsonNode();

		StringWriter out = new StringWriter();
		String jsonText = out.toString();
		System.out.print(jsonText);

		Iterator iter = node.entrySet().iterator();
		//System.out.println("==iterate result==");
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();

			String key = (String) entry.getKey();

			if (entry.getKey().equals("id")) {
				//change id to data for jstree format object
				obj.put("data", entry.getValue());
			} else if (!key.equals("children")) {
				obj.put(key, entry.getValue());
			}
			if (entry.getKey().equals("children")) {
				//System.out.println(entry.getValue().getClass());
				LinkedList<JsonNode> list = (LinkedList) entry.getValue();
				// this.printList(children, writer);
				LinkedList newChildren = new LinkedList<JsonNode>();
				for (JsonNode tempNode : list) {
					// obj.put(entry.getKey(), value)
					JsonNode newObj = createNew(tempNode);
					newChildren.add(newObj);
				}
				obj.put("children", newChildren);
			}
			//add new map pairs here for hrefs and any other info we need
			obj.put("state", "open");
			obj.put("title", "titlehere");

		}
		//System.out.println("returning object" + obj);
		return obj;
		// System.out.println("obj="+obj.toJSONString().substring(0,obj.toJSONString().length()-1));//when
		// printing chop off the last curly brace?
		// means we can print out the children as though form same ojbect
	}

}
